<?php
namespace app\api\controller;
use think\Controller;
use think\Db;

class Pay extends Common
{
    //微信支付回调验证
    public function notify() {
        //获取微信返回的数据结果
        $postData = file_get_contents("php://input");
        //将结果转换成数组
        $getData = $this->xmlstr_to_array($postData);

        if($getData['total_fee'] && ($getData['result_code'] == 'SUCCESS')){
            $order_sn_submit = trim($getData['out_trade_no']);
            // 以下是生成log测试
            // file_put_contents("../log.txt", $order_sn_submit, FILE_APPEND);

            // 更新库存
            // 根据提交订单号获取订单ID $order['id']
            $order = Db::name('order')->where('order_sn_submit', $order_sn_submit)->find();
            // 根据订单ID获取所有订单商品
            $goods = Db::name('order_goods')->where('oid', $order['id'])->select();
            // 更新商品库存(减少 setDec)
            foreach ($goods as $key => $value) {
                Db::name('goods')->where('id', $goods[$key]['gid'])->setDec('store', $goods[$key]['num']);
            }

            // 更新用户消费累计
            $uid = $order['uid'];
            $amount = $order['amount'];
            $total_amount = Db::name('user')->where('id', $uid)->value('total_amount') + $amount; //需更新的消费
            Db::name('user')->where('id', $uid)->setField('total_amount', number_format($total_amount, 2));

            //更新数据表订单状态
            Db::name('order')->where('order_sn_submit', $order_sn_submit)->update(['order_status'=>2]);

            // 第三季升级分销功能
            // 支付成功：后台开启分销功能，此用户有上级，改分销订单表中状态为已冻结，用户表更新冻结佣金
            if($res = $this->checkDistribute($uid)){
                Db::name('distribute')->where('order_sn', $order['order_sn'])->update(['state'=>1]);
                // 获取用户ID和对应佣金
                $dis_data = Db::name('distribute')->where('order_sn', $order['order_sn'])->column('uid,money');
                //更新用户表冻结佣金
                foreach ($dis_data as $key => $value) {
                    Db::name('user')->where('id', $key)->setInc('money_frozen', $value);
                }
            }

            echo "success";
        }else{
            echo "error";
        }
    }

    public function xmlstr_to_array($xmlstr){
        libxml_disable_entity_loader(true);
        $xmlstring = simplexml_load_string($xmlstr, 'SimpleXMLElement', LIBXML_NOCDATA);
        $val = json_decode(json_encode($xmlstring),true);
        return $val;
    }

}
